home *** CD-ROM | disk | FTP | other *** search
/ MacAddict 108 / MacAddict108.iso / Software / Internet & Communication / WordPress 1.5.1.dmg / wordpress / wp-admin / upgrade-functions.php < prev    next >
Encoding:
PHP Script  |  2005-03-29  |  24.4 KB  |  706 lines

  1. <?php
  2.  
  3. require_once(ABSPATH . '/wp-admin/admin-functions.php');
  4. require_once(ABSPATH . '/wp-admin/upgrade-schema.php');
  5. // Functions to be called in install and upgrade scripts
  6. function upgrade_all() {
  7.     populate_options();
  8.     upgrade_100();
  9.     upgrade_101();
  10.     upgrade_110();
  11.     upgrade_130();
  12.     save_mod_rewrite_rules();
  13. }
  14.  
  15. function upgrade_100() {
  16.     global $wpdb;
  17.  
  18.     // Get the title and ID of every post, post_name to check if it already has a value
  19.     $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
  20.     if ($posts) {
  21.         foreach($posts as $post) {
  22.             if ('' == $post->post_name) { 
  23.                 $newtitle = sanitize_title($post->post_title);
  24.                 $wpdb->query("UPDATE $wpdb->posts SET post_name = '$newtitle' WHERE ID = '$post->ID'");
  25.             }
  26.         }
  27.     }
  28.     
  29.     $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
  30.     foreach ($categories as $category) {
  31.         if ('' == $category->category_nicename) { 
  32.             $newtitle = sanitize_title($category->cat_name);
  33.             $wpdb->query("UPDATE $wpdb->categories SET category_nicename = '$newtitle' WHERE cat_ID = '$category->cat_ID'");
  34.         }
  35.     }
  36.  
  37.  
  38.     $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
  39.     WHERE option_name LIKE 'links_rating_image%'
  40.     AND option_value LIKE 'wp-links/links-images/%'");
  41.  
  42.     $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
  43.     if ($done_ids) :
  44.         foreach ($done_ids as $done_id) :
  45.             $done_posts[] = $done_id->post_id;
  46.         endforeach;
  47.         $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
  48.     else:
  49.         $catwhere = '';
  50.     endif;
  51.     
  52.     $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
  53.     if ($allposts) :
  54.         foreach ($allposts as $post) {
  55.             // Check to see if it's already been imported
  56.             $cat = $wpdb->get_row("SELECT * FROM $wpdb->post2cat WHERE post_id = $post->ID AND category_id = $post->post_category");
  57.             if (!$cat && 0 != $post->post_category) { // If there's no result
  58.                 $wpdb->query("
  59.                     INSERT INTO $wpdb->post2cat
  60.                     (post_id, category_id)
  61.                     VALUES
  62.                     ('$post->ID', '$post->post_category')
  63.                     ");
  64.             }
  65.         }
  66.     endif;
  67. }
  68.  
  69. function upgrade_101() {
  70.     global $wpdb;
  71.  
  72.     // Clean up indices, add a few
  73.     add_clean_index($wpdb->posts, 'post_name');
  74.     add_clean_index($wpdb->posts, 'post_status');
  75.     add_clean_index($wpdb->categories, 'category_nicename');
  76.     add_clean_index($wpdb->comments, 'comment_approved');
  77.     add_clean_index($wpdb->comments, 'comment_post_ID');
  78.     add_clean_index($wpdb->links , 'link_category');
  79.     add_clean_index($wpdb->links , 'link_visible');
  80. }
  81.  
  82.  
  83. function upgrade_110() {
  84.   global $wpdb;
  85.     
  86.     // Set user_nicename.
  87.     $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
  88.     foreach ($users as $user) {
  89.         if ('' == $user->user_nicename) { 
  90.             $newname = sanitize_title($user->user_nickname);
  91.             $wpdb->query("UPDATE $wpdb->users SET user_nicename = '$newname' WHERE ID = '$user->ID'");
  92.         }
  93.     }
  94.  
  95.     $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
  96.     foreach ($users as $row) {
  97.         if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
  98.                $wpdb->query('UPDATE '.$wpdb->users.' SET user_pass = MD5(\''.$row->user_pass.'\') WHERE ID = \''.$row->ID.'\'');
  99.         }
  100.     }
  101.  
  102.  
  103.     // Get the GMT offset, we'll use that later on
  104.     $all_options = get_alloptions_110();
  105.  
  106.     $time_difference = $all_options->time_difference;
  107.  
  108.     $server_time = time()+date('Z');
  109.     $weblogger_time = $server_time + $time_difference*3600;
  110.     $gmt_time = time();
  111.  
  112.     $diff_gmt_server = ($gmt_time - $server_time) / 3600;
  113.     $diff_weblogger_server = ($weblogger_time - $server_time) / 3600;
  114.     $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
  115.     $gmt_offset = -$diff_gmt_weblogger;
  116.  
  117.     // Add a gmt_offset option, with value $gmt_offset
  118.     add_option('gmt_offset', $gmt_offset);
  119.  
  120.     // Check if we already set the GMT fields (if we did, then
  121.     // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
  122.     // <michel_v> I just slapped myself silly for not thinking about it earlier
  123.     $got_gmt_fields = ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00') ? false : true;
  124.  
  125.     if (!$got_gmt_fields) {
  126.  
  127.         // Add or substract time to all dates, to get GMT dates
  128.         $add_hours = intval($diff_gmt_weblogger);
  129.         $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
  130.         $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
  131.         $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
  132.         $wpdb->query("UPDATE $wpdb->posts SET post_modified_gmt = DATE_ADD(post_modified, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE) WHERE post_modified != '0000-00-00 00:00:00'");
  133.         $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
  134.         $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
  135.     }
  136.  
  137. }
  138.  
  139. function upgrade_130() {
  140.     global $wpdb, $table_prefix;
  141.  
  142.     // Remove extraneous backslashes.
  143.     $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
  144.     if ($posts) {
  145.         foreach($posts as $post) {
  146.             $post_content = addslashes(deslash($post->post_content));
  147.             $post_title = addslashes(deslash($post->post_title));
  148.             $post_excerpt = addslashes(deslash($post->post_excerpt));
  149.             if ( empty($post->guid) )
  150.                 $guid = get_permalink($post->ID);
  151.             else
  152.                 $guid = $post->guid;
  153.  
  154.             $wpdb->query("UPDATE $wpdb->posts SET post_title = '$post_title', post_content = '$post_content', post_excerpt = '$post_excerpt', guid = '$guid' WHERE ID = '$post->ID'");
  155.         }
  156.     }
  157.  
  158.     // Remove extraneous backslashes.
  159.     $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
  160.     if ($comments) {
  161.         foreach($comments as $comment) {
  162.             $comment_content = addslashes(deslash($comment->comment_content));
  163.             $comment_author = addslashes(deslash($comment->comment_author));
  164.             $wpdb->query("UPDATE $wpdb->comments SET comment_content = '$comment_content', comment_author = '$comment_author' WHERE comment_ID = '$comment->comment_ID'");
  165.         }
  166.     }
  167.  
  168.     // Remove extraneous backslashes.
  169.     $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
  170.     if ($links) {
  171.         foreach($links as $link) {
  172.             $link_name = addslashes(deslash($link->link_name));
  173.             $link_description = addslashes(deslash($link->link_description));
  174.             $wpdb->query("UPDATE $wpdb->links SET link_name = '$link_name', link_description = '$link_description' WHERE link_id = '$link->link_id'");
  175.         }
  176.     }
  177.  
  178.     // The "paged" option for what_to_show is no more.
  179.     if ($wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = 'what_to_show'") == 'paged') {
  180.         $wpdb->query("UPDATE $wpdb->options SET option_value = 'posts' WHERE option_name = 'what_to_show'");
  181.     }
  182.  
  183.         $active_plugins = __get_option('active_plugins');
  184.  
  185.         // If plugins are not stored in an array, they're stored in the old
  186.         // newline separated format.  Convert to new format.
  187.         if ( !is_array( $active_plugins ) ) {
  188.             $active_plugins = explode("\n", trim($active_plugins));
  189.             update_option('active_plugins', $active_plugins);
  190.         }
  191.  
  192.     // Obsolete tables
  193.     $wpdb->query('DROP TABLE IF EXISTS ' . $table_prefix . 'optionvalues');
  194.     $wpdb->query('DROP TABLE IF EXISTS ' . $table_prefix . 'optiontypes');
  195.     $wpdb->query('DROP TABLE IF EXISTS ' . $table_prefix . 'optiongroups');
  196.     $wpdb->query('DROP TABLE IF EXISTS ' . $table_prefix . 'optiongroup_options');
  197.  
  198.     // Update comments table to use comment_type
  199.     $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
  200.     $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
  201.  
  202.     // Some versions have multiple duplicate option_name rows with the same values
  203.     $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
  204.     foreach ( $options as $option ) {
  205.         if ( 1 != $option->dupes ) { // Could this be done in the query?
  206.             $limit = $option->dupes - 1;
  207.             $dupe_ids = $wpdb->get_col("SELECT option_id FROM $wpdb->options WHERE option_name = '$option->option_name' LIMIT $limit");
  208.             $dupe_ids = join($dupe_ids, ',');
  209.             $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
  210.         }
  211.     }
  212.  
  213.     make_site_theme();
  214. }
  215.  
  216. // The functions we use to actually do stuff
  217.  
  218. // General
  219. function maybe_create_table($table_name, $create_ddl) {
  220.     global $wpdb;
  221.     foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
  222.         if ($table == $table_name) {
  223.             return true;
  224.         }
  225.     }
  226.     //didn't find it try to create it.
  227.     $q = $wpdb->query($create_ddl);
  228.     // we cannot directly tell that whether this succeeded!
  229.     foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
  230.         if ($table == $table_name) {
  231.             return true;
  232.         }
  233.     }
  234.     return false;
  235. }
  236.  
  237. function drop_index($table, $index) {
  238.     global $wpdb;
  239.     $wpdb->hide_errors();
  240.     $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
  241.     // Now we need to take out all the extra ones we may have created
  242.     for ($i = 0; $i < 25; $i++) {
  243.         $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
  244.     }
  245.     $wpdb->show_errors();
  246.     return true;
  247. }
  248.  
  249. function add_clean_index($table, $index) {
  250.     global $wpdb;
  251.     drop_index($table, $index);
  252.     $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
  253.     return true;
  254. }
  255.  
  256. /**
  257.  ** maybe_add_column()
  258.  ** Add column to db table if it doesn't exist.
  259.  ** Returns:  true if already exists or on successful completion
  260.  **           false on error
  261.  */
  262. function maybe_add_column($table_name, $column_name, $create_ddl) {
  263.     global $wpdb, $debug;
  264.     foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  265.         if ($debug) echo("checking $column == $column_name<br />");
  266.         if ($column == $column_name) {
  267.             return true;
  268.         }
  269.     }
  270.     //didn't find it try to create it.
  271.     $q = $wpdb->query($create_ddl);
  272.     // we cannot directly tell that whether this succeeded!
  273.     foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  274.         if ($column == $column_name) {
  275.             return true;
  276.         }
  277.     }
  278.     return false;
  279. }
  280.  
  281.  
  282. // get_alloptions as it was for 1.2.
  283. function get_alloptions_110() {
  284.     global $wpdb;
  285.     if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) {
  286.         foreach ($options as $option) {
  287.             // "When trying to design a foolproof system, 
  288.             //  never underestimate the ingenuity of the fools :)" -- Dougal
  289.             if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  290.             if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  291.             if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  292.             $all_options->{$option->option_name} = stripslashes($option->option_value);
  293.         }
  294.     }
  295.     return $all_options;
  296. }
  297.  
  298. // Version of get_option that is private to install/upgrade.
  299. function __get_option($setting) {
  300.     global $wpdb;
  301.  
  302.     $option = $wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting'");
  303.  
  304.     @ $kellogs = unserialize($option);
  305.     if ($kellogs !== FALSE)
  306.         return $kellogs;
  307.     else
  308.         return $option;
  309. }
  310.  
  311. function deslash($content) {
  312.     // Note: \\\ inside a regex denotes a single backslash.
  313.  
  314.     // Replace one or more backslashes followed by a single quote with
  315.     // a single quote.
  316.     $content = preg_replace("/\\\+'/", "'", $content);
  317.  
  318.     // Replace one or more backslashes followed by a double quote with
  319.     // a double quote.
  320.     $content = preg_replace('/\\\+"/', '"', $content);
  321.  
  322.     // Replace one or more backslashes with one backslash.
  323.     $content = preg_replace("/\\\+/", "\\", $content);
  324.  
  325.     return $content;
  326. }
  327.  
  328. function dbDelta($queries, $execute = true) {
  329.     global $wpdb;
  330.     
  331.     // Seperate individual queries into an array
  332.     if( !is_array($queries) ) {
  333.         $queries = explode( ';', $queries );
  334.         if('' == $queries[count($queries) - 1]) array_pop($queries);
  335.     }
  336.     
  337.     $cqueries = array(); // Creation Queries
  338.     $iqueries = array(); // Insertion Queries
  339.     $for_update = array();
  340.     
  341.     // Create a tablename index for an array ($cqueries) of queries
  342.     foreach($queries as $qry) {
  343.         if(preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
  344.             $cqueries[strtolower($matches[1])] = $qry;
  345.             $for_update[$matches[1]] = 'Created table '.$matches[1];
  346.         }
  347.         else if(preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
  348.             array_unshift($cqueries, $qry);
  349.         }
  350.         else if(preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
  351.             $iqueries[] = $qry;
  352.         }
  353.         else if(preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
  354.             $iqueries[] = $qry;
  355.         }
  356.         else {
  357.             // Unrecognized query type
  358.         }
  359.     }    
  360.  
  361.     // Check to see which tables and fields exist
  362.     if($tables = $wpdb->get_col('SHOW TABLES;')) {
  363.         // For every table in the database
  364.         foreach($tables as $table) {
  365.             // If a table query exists for the database table...
  366.             if( array_key_exists(strtolower($table), $cqueries) ) {
  367.                 // Clear the field and index arrays
  368.                 unset($cfields);
  369.                 unset($indices);
  370.                 // Get all of the field names in the query from between the parens
  371.                 preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2);
  372.                 $qryline = trim($match2[1]);
  373.  
  374.                 // Separate field lines into an array
  375.                 $flds = explode("\n", $qryline);
  376.  
  377.                 //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
  378.                 
  379.                 // For every field line specified in the query
  380.                 foreach($flds as $fld) {
  381.                     // Extract the field name
  382.                     preg_match("|^([^ ]*)|", trim($fld), $fvals);
  383.                     $fieldname = $fvals[1];
  384.                     
  385.                     // Verify the found field name
  386.                     $validfield = true;
  387.                     switch(strtolower($fieldname))
  388.                     {
  389.                     case '':
  390.                     case 'primary':
  391.                     case 'index':
  392.                     case 'fulltext':
  393.                     case 'unique':
  394.                     case 'key':
  395.                         $validfield = false;
  396.                         $indices[] = trim(trim($fld), ", \n");
  397.                         break;
  398.                     }
  399.                     $fld = trim($fld);
  400.                     
  401.                     // If it's a valid field, add it to the field array
  402.                     if($validfield) {
  403.                         $cfields[strtolower($fieldname)] = trim($fld, ", \n");
  404.                     }
  405.                 }
  406.                 
  407.                 // Fetch the table column structure from the database
  408.                 $tablefields = $wpdb->get_results("DESCRIBE {$table};");
  409.                                 
  410.                 // For every field in the table
  411.                 foreach($tablefields as $tablefield) {                
  412.                     // If the table field exists in the field array...
  413.                     if(array_key_exists(strtolower($tablefield->Field), $cfields)) {
  414.                         // Get the field type from the query
  415.                         preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
  416.                         $fieldtype = $matches[1];
  417.  
  418.                         // Is actual field type different from the field type in query?
  419.                         if($tablefield->Type != $fieldtype) {
  420.                             // Add a query to change the column type
  421.                             $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
  422.                             $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
  423.                         }
  424.                         
  425.                         // Get the default value from the array
  426.                             //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
  427.                         if(preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
  428.                             $default_value = $matches[1];
  429.                             if($tablefield->Default != $default_value)
  430.                             {
  431.                                 // Add a query to change the column's default value
  432.                                 $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
  433.                                 $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
  434.                             }
  435.                         }
  436.  
  437.                         // Remove the field from the array (so it's not added)
  438.                         unset($cfields[strtolower($tablefield->Field)]);
  439.                     }
  440.                     else {
  441.                         // This field exists in the table, but not in the creation queries?
  442.                     }
  443.                 }
  444.  
  445.                 // For every remaining field specified for the table
  446.                 foreach($cfields as $fieldname => $fielddef) {
  447.                     // Push a query line into $cqueries that adds the field to that table
  448.                     $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
  449.                     $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
  450.                 }
  451.                 
  452.                 // Index stuff goes here
  453.                 // Fetch the table index structure from the database
  454.                 $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
  455.                 
  456.                 if($tableindices) {
  457.                     // Clear the index array
  458.                     unset($index_ary);
  459.  
  460.                     // For every index in the table
  461.                     foreach($tableindices as $tableindex) {
  462.                         // Add the index to the index data array
  463.                         $keyname = $tableindex->Key_name;
  464.                         $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
  465.                         $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
  466.                     }
  467.  
  468.                     // For each actual index in the index array
  469.                     foreach($index_ary as $index_name => $index_data) {
  470.                         // Build a create string to compare to the query
  471.                         $index_string = '';
  472.                         if($index_name == 'PRIMARY') {
  473.                             $index_string .= 'PRIMARY ';
  474.                         }
  475.                         else if($index_data['unique']) {
  476.                             $index_string .= 'UNIQUE ';
  477.                         }
  478.                         $index_string .= 'KEY ';
  479.                         if($index_name != 'PRIMARY') {
  480.                             $index_string .= $index_name;
  481.                         }
  482.                         $index_columns = '';
  483.                         // For each column in the index
  484.                         foreach($index_data['columns'] as $column_data) {                    
  485.                             if($index_columns != '') $index_columns .= ',';
  486.                             // Add the field to the column list string
  487.                             $index_columns .= $column_data['fieldname'];
  488.                             if($column_data['subpart'] != '') {
  489.                                 $index_columns .= '('.$column_data['subpart'].')';
  490.                             }
  491.                         }
  492.                         // Add the column list to the index create string 
  493.                         $index_string .= ' ('.$index_columns.')';
  494.  
  495.                         if(!(($aindex = array_search($index_string, $indices)) === false)) {
  496.                             unset($indices[$aindex]);
  497.                             //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br/>Found index:".$index_string."</pre>\n";
  498.                         }
  499.                         //else echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br/><b>Did not find index:</b>".$index_string."<br/>".print_r($indices, true)."</pre>\n";
  500.                     }
  501.                 }
  502.  
  503.                 // For every remaining index specified for the table
  504.                 foreach($indices as $index) {
  505.                     // Push a query line into $cqueries that adds the index to that table
  506.                     $cqueries[] = "ALTER TABLE {$table} ADD $index";
  507.                     $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
  508.                 }
  509.  
  510.                 // Remove the original table creation query from processing
  511.                 unset($cqueries[strtolower($table)]);
  512.                 unset($for_update[strtolower($table)]);
  513.             } else {
  514.                 // This table exists in the database, but not in the creation queries?
  515.             }
  516.         }
  517.     }
  518.  
  519.     $allqueries = array_merge($cqueries, $iqueries);
  520.     if($execute) {
  521.         foreach($allqueries as $query) {
  522.             //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
  523.             $wpdb->query($query);
  524.         }
  525.     }
  526.  
  527.     return $for_update;
  528. }
  529.  
  530. function make_db_current() {
  531.     global $wp_queries;
  532.  
  533.     $alterations = dbDelta($wp_queries);
  534.     echo "<ol>\n";
  535.     foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
  536.     echo "</ol>\n";
  537. }
  538.  
  539. function make_db_current_silent() {
  540.     global $wp_queries;
  541.  
  542.     $alterations = dbDelta($wp_queries);
  543. }
  544.  
  545. function make_site_theme_from_oldschool($theme_name, $template) {
  546.     $home_path = get_home_path();
  547.     $site_dir = ABSPATH . "wp-content/themes/$template";
  548.  
  549.     if (! file_exists("$home_path/index.php"))
  550.         return false;
  551.  
  552.     // Copy files from the old locations to the site theme.
  553.     // TODO: This does not copy arbitarary include dependencies.  Only the
  554.     // standard WP files are copied.
  555.     $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
  556.  
  557.     foreach ($files as $oldfile => $newfile) {
  558.         if ($oldfile == 'index.php')
  559.             $oldpath = $home_path;
  560.         else
  561.             $oldpath = ABSPATH;
  562.  
  563.         if ($oldfile == 'index.php') { // Check to make sure it's not a new index
  564.             $index = implode('', file("$oldpath/$oldfile"));
  565.             if ( strstr( $index, 'WP_USE_THEMES' ) ) {
  566.                 if (! @copy(ABSPATH . 'wp-content/themes/default/index.php', "$site_dir/$newfile"))
  567.                     return false;
  568.                 continue; // Don't copy anything
  569.                 }
  570.         }
  571.  
  572.         if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
  573.             return false;
  574.  
  575.         chmod("$site_dir/$newfile", 0777);
  576.  
  577.         // Update the blog header include in each file.
  578.         $lines = explode("\n", implode('', file("$site_dir/$newfile")));
  579.         if ($lines) {
  580.             $f = fopen("$site_dir/$newfile", 'w');
  581.  
  582.             foreach ($lines as $line) {
  583.                 if (preg_match('/require.*wp-blog-header/', $line))
  584.                     $line = '//' . $line;
  585.  
  586.                 // Update stylesheet references.
  587.                 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
  588.  
  589.                 // Update comments template inclusion.
  590.                 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
  591.  
  592.                 fwrite($f, "{$line}\n");
  593.             }
  594.             fclose($f);
  595.         }
  596.     }
  597.  
  598.     // Add a theme header.
  599.     $header = "/*\nTheme Name: $theme_name\nTheme URI: " . __get_option('siteurl') . "\nDescription: A theme automatically created by the upgrade.\nVersion: 1.0\nAuthor: Moi\n*/\n";
  600.  
  601.     $stylelines = file_get_contents("$site_dir/style.css");
  602.     if ($stylelines) {
  603.         $f = fopen("$site_dir/style.css", 'w');
  604.  
  605.         fwrite($f, $header);
  606.         fwrite($f, $stylelines);
  607.         fclose($f);
  608.     }
  609.  
  610.     return true;
  611. }
  612.  
  613. function make_site_theme_from_default($theme_name, $template) {
  614.     $site_dir = ABSPATH . "wp-content/themes/$template";
  615.     $default_dir = ABSPATH . 'wp-content/themes/default';
  616.  
  617.     // Copy files from the default theme to the site theme.
  618.     //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
  619.  
  620.     $theme_dir = @ dir("$default_dir");
  621.     if ($theme_dir) {
  622.         while(($theme_file = $theme_dir->read()) !== false) {
  623.             if (is_dir("$default_dir/$theme_file"))
  624.                 continue;
  625.             if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
  626.                 return;
  627.             chmod("$site_dir/$theme_file", 0777);
  628.         }
  629.     }
  630.  
  631.     // Rewrite the theme header.
  632.     $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
  633.     if ($stylelines) {
  634.         $f = fopen("$site_dir/style.css", 'w');
  635.  
  636.         foreach ($stylelines as $line) {
  637.             if (strstr($line, "Theme Name:")) $line = "Theme Name: $theme_name";
  638.             elseif (strstr($line, "Theme URI:")) $line = "Theme URI: " . __get_option('siteurl');
  639.             elseif (strstr($line, "Description:")) $line = "Description: Your theme";
  640.             elseif (strstr($line, "Version:")) $line = "Version: 1";
  641.             elseif (strstr($line, "Author:")) $line = "Author: You";
  642.             fwrite($f, "{$line}\n");
  643.         }
  644.         fclose($f);
  645.     }
  646.  
  647.     // Copy the images.
  648.     umask(0);
  649.     if (! mkdir("$site_dir/images", 0777)) {
  650.         return false;
  651.     }
  652.  
  653.     $images_dir = @ dir("$default_dir/images");
  654.     if ($images_dir) {
  655.         while(($image = $images_dir->read()) !== false) {
  656.             if (is_dir("$default_dir/images/$image"))
  657.                 continue;
  658.             if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
  659.                 return;
  660.             chmod("$site_dir/images/$image", 0777);
  661.         }
  662.     }
  663. }
  664.  
  665. // Create a site theme from the default theme.
  666. function make_site_theme() {
  667.     // Name the theme after the blog.
  668.     $theme_name = __get_option('blogname');
  669.     $template = sanitize_title($theme_name);
  670.     $site_dir = ABSPATH . "wp-content/themes/$template";
  671.  
  672.     // If the theme already exists, nothing to do.
  673.     if ( is_dir($site_dir)) {
  674.         return false;
  675.     }
  676.  
  677.     // We must be able to write to the themes dir.
  678.     if (! is_writable(ABSPATH . "wp-content/themes")) {
  679.         return false;
  680.     }
  681.  
  682.     umask(0);
  683.     if (! mkdir($site_dir, 0777)) {
  684.         return false;
  685.     }
  686.  
  687.     if (file_exists(ABSPATH . 'wp-layout.css')) {
  688.         if (! make_site_theme_from_oldschool($theme_name, $template)) {
  689.             // TODO:  rm -rf the site theme directory.
  690.             return false;
  691.         }
  692.     } else {
  693.         if (! make_site_theme_from_default($theme_name, $template))
  694.             // TODO:  rm -rf the site theme directory.
  695.             return false;
  696.     }
  697.  
  698.     // Make the new site theme active.
  699.     $current_template = __get_option('template');
  700.     if ($current_template == 'default') {
  701.         update_option('template', $template);
  702.         update_option('stylesheet', $template);
  703.     }
  704.     return $template;
  705. }
  706. ?>